package com.apes.auto.autoparts.vin;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.apes.auto.autoparts.DataSource;
import com.apes.auto.autoparts.repository.AutopartsDao;
import com.apes.framework.api.DomainService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class InnerPartsListSearcher<T,R> extends DomainService implements PartsListSearcher<T,R> {

    @Autowired
    AutopartsDao autopartsDao;

    @Override
    public R parse(T element) {
        return (R) getParts((JSONObject) element);
    }

    @Override
    public String[] getSource() {
        return new String[]{DataSource.INNER.name()};
    }


    /***
     * 需获取的数据
     * epc_bwm
     * epc_picture
     * epc_oe_pjmc
     *  -- 对应的版本A
     *   SELECT T.*,T.ROWID FROM SJZX.EPC_BMW   T ;
     *   -- 对应的图片表，通过逗号分隔
     *   SELECT T.*,T.ROWID FROM  SJZX.EPC_PICTURE T ;
     *   -- 对应epc的oe编译结果
     *   SELECT T.*,T.ROWID FROM  EPC_OE_PJMC T;
     *   -- 热点图
     *   SELECT T.*,T.ROWID FROM SJZX.EPC_PICTURE_POINT  T ;
     */


    /***
     * 通过 epc_bbmc 查询对应表 例如 bwm --->  epc_bwm
     * @param param
     * @return
     */
    private JSONObject getParts(JSONObject param) {
        JSONObject returnJson = new JSONObject();
        String tableName = "EPC_" + param.getString("epcVersion");

        //关联查询主数据
        JSONArray mainArray = autopartsDao.getAnalysisParts(param, tableName);
        JSONArray cacheArray = new JSONArray();
        JSONObject mainJson;
        for( int i = 0, len = mainArray.size(); i < len; i++ ) {
            mainJson = mainArray.getJSONObject(i);
            // 查询关联的图片信息
            JSONArray imageUrls = autopartsDao.getImageUrl(mainJson);
            if(imageUrls.size() != 0){
                mainJson.put("imageUrls", imageUrls.getJSONObject(0).getString("IMGNAME"));
            } else {
                mainJson.put("imageUrls", "");
            }
            cacheArray.add(invoke("autoparts.partsListConvert", mainJson));
        }
        // TODO: 查询热点

        returnJson.put("parts", cacheArray);

        return returnJson;
    }
}
